/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mylhyl.zxing.scanner;

import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import ohos.aafwk.ability.delegation.IAbilityDelegator;
import ohos.ai.cv.common.ConnectionCallback;
import ohos.ai.cv.common.VisionManager;
import ohos.ai.cv.qrcode.IBarcodeDetector;
import ohos.app.Context;
import org.junit.Assert;
import org.junit.Test;

public class VisionManagerInitTest {

    @Test
    public void qrEncodeBuild() {

        Object mLock = new Object(); // 同步锁
        final boolean[] isFinish = new boolean[1];
        final int[] result = {-1};

        IAbilityDelegator sAbilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
        Context context = sAbilityDelegator.getAppContext();
        ConnectionCallback connectionCallback = new ConnectionCallback() {
            @Override
            public void onServiceConnect() {
                IBarcodeDetector barcodeDetector = VisionManager.getBarcodeDetector(context);
                final int SAMPLE_LENGTH = 152;
                byte[] byteArray = new byte[SAMPLE_LENGTH * SAMPLE_LENGTH * 4];
                result[0] = barcodeDetector.detect("This is a qrCode", byteArray, SAMPLE_LENGTH, SAMPLE_LENGTH);
                barcodeDetector.release();
                VisionManager.destroy();
                isFinish[0] = true;
                synchronized (mLock) {
                    mLock.notifyAll(); // 回调执行完毕，唤醒主线程
                }
            }

            @Override
            public void onServiceDisconnect() {
                isFinish[0] = true;
                synchronized (mLock) {
                    mLock.notifyAll(); // 回调执行完毕，唤醒主线程
                }
            }
        };

        int results = VisionManager.init(context, connectionCallback);
        synchronized (mLock) {
            isFinish[0] = false;  // 设置锁条件
            while (isFinish[0] != true) {
                try {
                    mLock.wait(); // 等待唤醒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        Assert.assertSame(result[0], 0);
        Assert.assertSame(results, -1);
    }
}